﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using Microsoft.Win32;
using System.Collections;
using Pub;
using System.Runtime.InteropServices;
using System.Threading;

namespace LZQXT.Test.Forms.Reg
{
    public partial class FReg : Form
    {

        public List<RegistryKey> lstReg = new List<RegistryKey>();
        public int regIndex = 0;
        public string sKey = "";
        public string sVal = "";
        public string sGroup = "";

        public int i_typ = 0;
        public const int I_TYP_ADD = 1;
        public const int I_TYP_EDT = 2;
        public const int I_TYP_DEL = 3;

        [DllImport("user32.dll", EntryPoint = "SendMessageA")]

        private static extern int SendMessage(IntPtr hwnd, int wMsg, IntPtr wParam, string lParam);

        [DllImport("user32.dll", EntryPoint = "SendMessageA")]

        private static extern int SendMessage(IntPtr hwnd, int wMsg, IntPtr wParam, ref Rectangle lParam);

        //private static readonly IntPtr HWND_BROADCAST = new IntPtr(0xffff);

        const int WM_SETTINGCHANGE = 0x001A;

        const int HWND_BROADCAST = 0xffff;

        IntPtr result1;

        public enum SendMessageTimeoutFlags : uint
        {
            SMTO_NORMAL = 0x0000,
            SMTO_BLOCK = 0x0001,
            SMTO_ABORTIFHUNG = 0x0002,
            SMTO_NOTIMEOUTIFNOTHUNG = 0x0008
        }

        [DllImport("user32.dll", SetLastError = true, CharSet = CharSet.Auto)]
        public static extern IntPtr SendMessageTimeout(
            IntPtr windowHandle,
            uint Msg,
            IntPtr wParam,
            //IntPtr lParam,
            string lParam,
            SendMessageTimeoutFlags flags,
            uint timeout,
            out IntPtr result
        );

        public void ChangeReg()
        {
            //通知所有打开的程序注册表已修改 
            SendMessageTimeout(new IntPtr(HWND_BROADCAST), WM_SETTINGCHANGE, IntPtr.Zero,
                //IntPtr.Zero,
                "Environment",
                SendMessageTimeoutFlags.SMTO_ABORTIFHUNG, 5000, out result1);
            //CDebug.Send("消息发送完成");
        }

        Thread t1;

        public void refReg()
        {
            t1 = new Thread(new ThreadStart(ChangeReg));
            t1.Start();
        }

        public FReg()
        {
            InitializeComponent();
        }

        private void FReg_Load(object sender, EventArgs e)
        {
            listView1.Dock = DockStyle.Fill;
            panel1.Visible = false;

            getEnvironment_II();
        }


        private void button1_Click(object sender, EventArgs e)
        {

        }

        private void button2_Click(object sender, EventArgs e)
        {

        }

        private void btn_Click(object sender, EventArgs e)
        {
            int i_btn = 0;

            if (sender is Int32) i_btn = Convert.ToInt32(sender);
            if (sender is MenuItem) i_btn = Convert.ToInt32(((MenuItem)sender).Tag);
            if (sender is ToolStripMenuItem) i_btn = Convert.ToInt32(((ToolStripMenuItem)sender).Tag);
            if (sender is Button) i_btn = Convert.ToInt32(((Button)sender).Tag);
            if (sender is ToolStripButton) i_btn = Convert.ToInt32(((ToolStripButton)sender).Tag);


            switch (i_btn)
            {
                case 1:     //add
                    panel1.Visible = true;
                    i_typ = I_TYP_ADD;
                    break;
                case 2:     //edit
                    i_typ = I_TYP_EDT;
                    sVal = richTextBox1.Text;

                    if (CPub.MsgBox(sGroup + "\n确定要保存 [" + sKey + "=\n" + sVal + "] 吗?", "保存"))
                    {
                        sVal = sVal.Replace("\n", "");
                        lstReg[regIndex].SetValue(sKey, sVal);
                        panel1.Visible = false;

                        refReg();
                    }

                    break;
                case 3:     //delete
                    if (CPub.MsgBox(sGroup + "\n确定要删除 [" + sKey + "=" + sVal + "] 吗?", "删除"))
                    {
                        lstReg[regIndex].DeleteValue(sKey);
                        listView1.SelectedItems[0].Remove();

                        refReg();
                    }


                    break;
                case 4:     //ref

                    getEnvironment_II();
                    break;
                case 11:     //add - save
                    sKey = tboxKey.Text;
                    sVal = tboxVal.Text;
                    if (CPub.MsgBox(sGroup + "\n确定要保存 [" + sKey + "=" + sVal + "] 吗?", "保存"))
                    {
                        lstReg[regIndex].SetValue(sKey, sVal);
                        panel1.Visible = false;

                        //wstring szParam = _T( "Environment" );
                        //::SendMessage( HWND_BROADCAST, WM_SETTINGCHANGE, 0, (LPARAM)szParam.c_str() );

                        //SendMessageTimeout(HWND_BROADCAST, WM_SETTINGCHANGE, 0,LPARAM("Environment"), SMTO_ABORTIFHUNG, 5000, &MsgResult);

                        //SendMessage(HWND_BROADCAST, WM_SETTINGCHANGE, IntPtr.Zero, "Environment");

                        refReg();
                    }

                    break;
                case 12:     //cancel

                    panel1.Visible = false;
                    break;

            }
        }

        public void getEnvironment_I()
        {
            // 把环境变量中所有的值取出来，放到变量environment中
            IDictionary environment = Environment.GetEnvironmentVariables();

            // 打印表头
            Console.WriteLine("环境变量名\t=\t环境变量值");
            // 遍历environment中所有键值
            foreach (DictionaryEntry de in environment)
            {
                // 打印出所有环境变量的名称和值
                //Console.WriteLine("{0}\t=\t{1}", environmentKey, environment[environmentKey].ToString());

                richTextBox1.AppendText(de.Key + "=" + de.Value + "\n");
            }
        }

        public void getEnvironment_II()
        {
            /*
            系统变量
            [HKLM\SYSTEM\ControlSet001\Control\Session Manager\Environment]
            [HKLM\SYSTEM\ControlSet002\Control\Session Manager\Environment]
            [HKLM\SYSTEM\CurrentControlSet\Control\Session Manager\Environment]

            用户变量
            [HKCU\Environment]
            */

            List<string> sPath = new List<string>();
            sPath.Add(@"[系统变量][HKLM\SYSTEM\ControlSet001\Control\Session Manager\Environment]");
            //sPath.Add(@"[系统变量][HKLM\SYSTEM\ControlSet002\Control\Session Manager\Environment]");
            //sPath.Add(@"[系统变量][HKLM\SYSTEM\CurrentControlSet\Control\Session Manager\Environment]");
            sPath.Add(@"[用户变量][HKCU\Environment]");

            listView1.Items.Clear();

            for (int j = 0; j < sPath.Count; j++)
            {
                listView1.Groups.Add(new ListViewGroup(sPath[j]));

                RegistryKey reg = null;
                if (CPub.findStrBetween(sPath[j], "[", "]") == "系统变量")
                    reg = Registry.LocalMachine;

                if (CPub.findStrBetween(sPath[j], "[", "]") == "用户变量")
                    reg = Registry.CurrentUser;

                string[] s1 = CPub.findStrBetween(sPath[j], 1, "[", "]").Split('\\');
                for (int i = 1; i < s1.Length; i++)
                {
                    RegistryKey reg1 = reg.OpenSubKey(s1[i], true);
                    reg = reg1;
                }
                lstReg.Add(reg);

                for (int i = 0; i < reg.ValueCount; i++)
                {
                    sKey = reg.GetValueNames()[i];
                    sVal = reg.GetValue(sKey).ToString();
                    //this.richTextBox1.AppendText(sKey + "=" + sVal + "\n");//读取path的值

                    ListViewItem item = new ListViewItem(sKey);
                    item.SubItems.Add(sVal);
                    item.Group = listView1.Groups[j];
                    item.Tag = j;
                    listView1.Items.Add(item);
                }
            }

            listView1.AutoResizeColumns(ColumnHeaderAutoResizeStyle.ColumnContent);
        }

        private void listView1_SelectedIndexChanged(object sender, EventArgs e)
        {
            if (listView1.SelectedItems.Count == 0)
                return;
            sKey = listView1.SelectedItems[0].SubItems[0].Text;
            sVal = listView1.SelectedItems[0].SubItems[1].Text;
            sVal = sVal.Replace(";", ";\n");
            richTextBox1.Text = sVal;
            regIndex = Convert.ToInt16(listView1.SelectedItems[0].Tag);
            sGroup = listView1.Groups[regIndex].ToString();

        }




    }
}
